// pages/manage/manage.js
const fs = wx.getFileSystemManager()
Page({
    data: {
        mode: 'managelist',
        tables: [],
        tableID: '',
        tableName: '',
        questions: [],

        showOptionDialog: false,
        questionModalValue: '',
        currentQuestionId: -1,
        submitType: 'create',
        optionButtons: [{text:'取消'}, {text:'确认'}],

        qrcode: '',
        codeTempFile: '',
        imgButtons: [{text:'关闭'}, {text:'保存'}],
        showImgDialog: false
    },

    onLoad: function (options) {
        this.setData({
            mode: options.mode,
            submitType: options.mode == 'manage' ? 'create' : 'update'
        })
        this.getAllTable()
    },

    /* --管理视图start-- */
    tableNameInput: function (e) {
        this.data.tableName = e.detail.value;
    },

    addQuestion: function () {
        let that = this;
        var questions = that.data.questions;
        var question = {
            q: '',
            op: [],
            type: -1
        };
        wx.showActionSheet({
            itemList: ['小文本', '单项选择', '多项选择', '大文本'],
            success: res => {
                question.type = res.tapIndex;
                question.op = [];
                question.q = '';
                questions.push(question);
                that.setData({
                    questions: questions
                });
            }
        })
    },

    removeOption: function (e) {
        let that = this;
        var questions = that.data.questions;
        wx.showModal({
            title: '确认删除',
            content: '删除选项 ' + questions[e.currentTarget.dataset.paidx].op[e.currentTarget.dataset.idx] + ' ？',
            success: res => {
                if (res.confirm) {
                    questions[e.currentTarget.dataset.paidx].op.splice(e.currentTarget.dataset.idx, 1);
                    that.setData({
                        questions: questions
                    })
                }
            }
        })
    },

    onQuestionInput: function (e) {
        let that = this;
        var questions = that.data.questions;
        questions[e.currentTarget.dataset.idx].q = e.detail.value;
        that.setData({
            questions: questions
        })
    },

    addOption: function (e) {
        this.setData({
            showOptionDialog: true,
            currentQuestionId: e.currentTarget.dataset.idx
        })
    },

    modalInput: function (e) {
        this.data.questionModalValue = e.detail.value
    },

    optionConfirm: function(e) {
        let that = this;
        if(e.detail.index == 1) {
            var questions = that.data.questions;
            questions[that.data.currentQuestionId].op.push(that.data.questionModalValue)
            that.setData({
                questions: questions,
                showOptionDialog: false,
                questionModalValue: '',
                currentQuestionId: -1
            })
        } else {
            this.setData({
                showOptionDialog: false,
                questionModalValue: '',
            })
        }
    },

    submitQuestion: function (e) {
        let that = this;
        if (that.data.questions.length == 0) {
            wx.showModal({
                title: '提示',
                content: '请为问卷添加问卷内容后再提交！',
                showCancel: false
            })
        } else {
            wx.showModal({
                cancelColor: 'cancelColor',
                title: '确认操作',
                content: '确认提交问卷？',
                success: res => {
                    if (res.confirm) {
                        if(that.data.submitType == 'create') {
                            that.createTable();
                        } else if(that.data.submitType == 'update') {
                            that.updateTable();
                        }
                    }
                }
            })
        }
    },

    /**
     * 上移问题
     */
    upque: function(e) {
        var idx = e.currentTarget.dataset.idx;
        if(idx != 0) {
            var questions = this.data.questions;
            var idx_q = questions[idx - 1];
            questions[idx - 1] = questions[idx];
            questions[idx] = idx_q;
            this.setData({ questions: questions })
        }
    },

    /**
     * 下移问题
     */
    downque: function(e) {
        var idx = e.currentTarget.dataset.idx;
        if(idx != this.data.questions.length - 1) {
            var questions = this.data.questions;
            var idx_q = questions[idx + 1];
            questions[idx + 1] = questions[idx];
            questions[idx] = idx_q;
            this.setData({ questions: questions })
        }
    },

    /**
     * 删除问题
     */
    deleteque: function(e) {
        var idx = e.currentTarget.dataset.idx;
        let that = this
        wx.showModal({
            title: '删除确认',
            content: '确认删除问题:' + that.data.questions[idx].q + '？',
            success: res => {
                if(res.confirm) {
                    var questions = that.data.questions;
                    questions.splice(idx, 1);
                    that.setData({ questions: questions })
                }
            }
        })
    },

    /**
     * 生成小程序码
     * @param {e} e 响应事件内容 
     */
    generateQrCode: function (e) {
        console.log(e.currentTarget.dataset.tid)
        let that = this
        wx.showLoading({
          title: '请求中...',
        })
        wx.cloud.callFunction({
            name: "getUnlimited",
            data: {
                tid: e.currentTarget.dataset.tid
            },
            complete: res => {
                console.log(res)
                if(res.result.errMsg == 'openapi.wxacode.getUnlimited:ok') {
                    var qrImg = "data:" + res.result.contentType + ";base64," + wx.arrayBufferToBase64(res.result.buffer)
                    var filename = 'code_' + Math.round(Math.random()*10000000) + '.jpg'
                    fs.writeFile({
                        filePath: wx.env.USER_DATA_PATH + '/' + filename,
                        data: res.result.buffer,
                        success: res => {
                            console.log(res)
                        }
                    })
                    that.setData({
                        qrcode: qrImg,
                        codeTempFile: filename,
                        showImgDialog: true
                    })
                }
                wx.hideLoading({})
            }
        })
    },

    /**
     * 小程序码窗口按钮点击事件
     * @param {*} e 
     */
    imgConfirm: function(e) {
        if(e.detail.index == 1) {
            this.saveImgToDisk()
        }
        this.setData({
            showImgDialog: false,
        })
    },

    /**
     * 二维码图片的长按保存
     */
    saveImgToDisk: function() {
        let that = this
        wx.showModal({
            title: '保存小程序码',
            content: '确认保存此小程序码？',
            success: res => {
                if(res.confirm && that.data.qrcode != '') {
                    wx.getSetting({
                        success: (res) => {
                            that.checkAndSave(res);
                        }
                    })
                } else if(that.data.qrcode == '') {
                    wx.showToast({
                        title: '请先点击生成!',
                        duration: 1000
                    })
                }
            }
        })
    },

    /**
     * 鉴权并保存图片到本地
     * @param {*} res 含有权限列表的系统设置
     */
    checkAndSave: function(res) {
        let that = this
        if (!res.authSetting['scope.writePhotosAlbum']) {
            wx.authorize({
                scope: 'scope.writePhotosAlbum',
                success:()=> {
                    wx.saveImageToPhotosAlbum({
                        filePath: wx.env.USER_DATA_PATH + '/' + that.data.codeTempFile,
                        success: res => {
                            if(res.errMsg == 'saveImageToPhotosAlbum:ok') {
                                wx.showToast({
                                    title: '保存完成',
                                    icon: 'none',
                                    duration: 1500
                                })
                                that.setData({
                                    qrcode: '',
                                    codeTempFile: '',
                                })
                            }
                        }
                    })
                }
            })
        }else{
            wx.saveImageToPhotosAlbum({
                filePath: wx.env.USER_DATA_PATH + '/' + that.data.codeTempFile,
                success: res => {
                    if(res.errMsg == 'saveImageToPhotosAlbum:ok') {
                        wx.showToast({
                            title: '保存完成',
                            icon: 'none',
                            duration: 1500
                        })
                    }
                }
            })
        }
    },

    /* else */
    getAllTable: function () {
        let that = this
        wx.showLoading({
            title: '加载中...',
        })
        const db = wx.cloud.database()
        db.collection('q_table').get({
            success: res => {
                that.setData({
                    tables: res.data
                })
                wx.hideLoading({})
            },
            fail: res => {
                wx.hideLoading({})
            }
        })
    },

    createTable: function () {
        let that = this
        wx.showLoading({
            title: '提交中...',
        })

        const doc = {
            _id: `${Math.random().toFixed(8)}_${Date.now()}`,
            'tableName': that.data.tableName,
            'createTime': new Date(),
            'content': that.data.questions
        }

        const db = wx.cloud.database()
        db.collection('q_table').add({
            data: doc,
            success: res => {
                this.getAllTable()
                that.setData({
                    mode: 'managelist'
                })
                wx.hideLoading({})
                wx.showToast({
                    title: '提交成功',
                })
            },
            fail: res => {
                wx.hideLoading({})
                wx.showToast({
                    title: '请稍后重试',
                })
            }
        })
    },

    deleteTable: function (e) {
        wx.showModal({
            title: '确认操作',
            content: '删除问卷： ' + e.currentTarget.dataset.tname + '？',
            success: res => {
                if (res.confirm) {
                    const db = wx.cloud.database()
                    db.collection('q_table').doc(e.currentTarget.dataset.tid).remove({
                        success: res => {
                            this.getAllTable()
                        },
                        fail: res => {
                            wx.showToast({
                                title: '请稍后重试',
                            })
                        }
                    })
                }
            }
        })
    },

    toUpdateTable: function (e) {
        this.data.tables.forEach(element => {
            if(element._id == e.currentTarget.dataset.tid) {
                this.setData({
                    mode: 'manage',
                    questions: element.content,
                    tableID: e.currentTarget.dataset.tid,
                    tableName: element.tableName,
                    submitType: 'update'
                })
            }
        });
    },

    updateTable: function () {
        let that = this
        wx.showLoading({
            title: '提交中...',
        })

        const doc = {
            'tableName': that.data.tableName,
            'updateTime': new Date(),
            'content': that.data.questions
        }

        const db = wx.cloud.database()
        db.collection('q_table').doc(that.data.tableID).update({
            data: doc,
            success: res => {
                this.getAllTable()
                that.setData({
                    mode: 'managelist'
                })
                wx.hideLoading({})
                wx.showToast({
                    title: '提交成功',
                })
            },
            fail: res => {
                wx.hideLoading({})
                wx.showToast({
                    title: '请稍后重试',
                })
            }
        })
    },

    refreshview: function() {
        this.setData({ questions: this.data.questions })
    }
})